from flask import request, json
from flask_cors import CORS
import requests
from model import *
from initdb import initdb
import redis

app = create_app()
app.app_context().push()
initdb()
CORS(app)
redis_conn = redis.Redis(host= 'redis', port = 6379, decode_responses=True)

@app.route('/query', methods=["POST", "GET"])
def dormlist():

    dormlist = redis_conn.hgetall('dormlist')
    if(dormlist):
        print('redis')
        return {
        "status": 1,
        "message": "Query Successful",
        "dormlist": json.dumps(dormlist)
    }

    else:
        dormlist = {}
        for dorm in Dorm.query.all():
            for unit in Unit.query.filter_by(dorm_id = dorm.id):
                sum = 0
                for room in Room.query.filter_by(unit_id = unit.id):
                    sum += room.rest
                dormlist["dorm" + str(dorm.dormid) + "unit" + str(unit.unitid)] = sum
        redis_conn.hmset("dormlist", dormlist)       
        return {
            "status": 1,
            "message": "Query Successful",
            "dormlist": json.dumps(dormlist)
        }
    # token = request.headers.get('Authorization')

    # if(token):
    #     Headers = {
    #         'Authorization': token
    #     }
    #     r = requests.get('http://jwt:5000/verify-token', headers=Headers)
    #     if(r.status_code == 200 and r.json().get("Valid")):
    #         dormlist = []
    #         for dorm in Dorm.query.all():
    #             for unit in Unit.query.filter_by(dorm_id = dorm.id):
    #                 sum = 0
    #                 for room in Room.query.filter_by(unit_id = unit.id):
    #                     sum += room.rest
    #                 temp = {
    #                     "dorm" + str(dorm.dormid) + " unit" + str(unit.unitid): sum
    #                 }
    #                 dormlist.append(temp)
    #         return {
    #             "status": 1,
    #             "id": r.json().get('id'),
    #             "message": "Query Successful",
    #             "dormlist": dormlist
    #         }
    #     else:
    #         return {
    #             "status": 0,
    #             "message": "Invalid token"
    #         }
    # else:
    #     return {
    #         "status": -1,
    #         "message": "Login first"
    #     }


if __name__ == "__main__":
    app.run(host = '0.0.0.0')